import operator
import time
from osv import osv, fields
from osv.orm import intersect
import tools.sql
from tools import config
from tools.translate import _
from datetime import datetime

class kdvn_log(osv.osv): 
    _name = 'kdvn.log'
    _description = 'KDVN Log'
    _order="name"
    
    def create_log(self,cr,uid,old_id,new_val,model_name):
        old_state=self.pool.get(model_name).browse(cr,uid,old_id)[0].state
        new_state=new_val['state']
        now=datetime.now()
        current_date=now.strftime("%Y-%m-%d %H:%M:%S")
        new_log={'name':current_date,'from_state':old_state,'to_state':new_state,'record_id':old_id[0],'model':model_name,'user':uid}
        new_log_id=self.create(cr,uid,new_log)
        return new_log_id
    
    def _fnc_act_from(self, cr, uid, ids, name, arg, context):
        res={}
        for kl in self.browse(cr,uid,ids):
            so=self.pool.get(kl.model)
            so_f_state=so.fields_get(cr,uid,fields='state')
            try:
                res[kl.id]=dict(so_f_state['state']['selection'])[kl.from_state]
                if res[kl.id].strip()=='':
                    res[kl.id]=kl.from_state
            except:
                res[kl.id]="Error, Please check !"
        return res
    
    
    def _fnc_act_to(self, cr, uid, ids, name, arg, context):
        res={}
        for kl in self.browse(cr,uid,ids):
            so=self.pool.get(kl.model)
            so_f_state=so.fields_get(cr,uid,fields='state')
            try:
                res[kl.id]=dict(so_f_state['state']['selection'])[kl.to_state]
                if res[kl.id].strip()=='':
                    res[kl.id]=kl.to_state
            except:
                res[kl.id]="Error, Please check !"
        return res
    _columns = {
            'name':fields.datetime('Date Changed',required=True,readonly=True,select=1),
            'from_state':fields.char('From State', size=128,readonly=True,select=1,required=True),
            'to_state':fields.char('To State',select=1,size=128,readonly=True,required=True),
            'record_id':fields.integer('Record ID',readonly=True,required=True,select=1),
            'user':fields.many2one('res.users','Changed By',readonly=True,required=True,select=1),
            'model':fields.char('Model',size=128,readonly=True,required=True,select=1),
            'from_state_act':fields.function(_fnc_act_from,string='From State',method=True,type='char'),
            'to_state_act':fields.function(_fnc_act_to,string='To State',method=True,type='char'),
                }
kdvn_log()
#raise osv.except_osv("E",self._name)